<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button @click="showAddCateDialog"
                     type="primary">添加分类</el-button>
        </el-col>
      </el-row>
      <!-- 表格 -->
      <tree-table :expand-type="false"
                  :selection-type="false"
                  :data="cateList"
                  :columns="columns"
                  show-index
                  index-text
                  border
                  class="treeTable">
        <!-- 是否有效 -->
        <template slot="isok"
                  slot-scope="scope">
          <i style="color:lightgreen"
             v-if="scope.row.catDeleted===0"
             class="el-icon-success"></i>
          <i style="color:red"
             v-else
             class="el-icon-error"></i>
        </template>

        <!-- 排序 -->
        <template slot="order"
                  slot-scope="scope">
          <el-tag size="mini"
                  v-if="scope.row.catLevel===0">一级</el-tag>
          <el-tag size="mini"
                  type="success"
                  v-else-if="scope.row.catLevel===1">二级</el-tag>
          <el-tag size="mini"
                  type="warning"
                  v-else>三级</el-tag>
        </template>

        <!-- 操作 -->
        <template slot="opt"
                  slot-scope="scope">
          <el-button size="mini"
                     type="primary"
                     icon="el-icon-edit"
                     @click="showEditDialog(scope.row.catId)">编辑</el-button>
          <el-button size="mini"
                     type="danger"
                     icon="el-icon-delete"
                     @click="removeUserById(scope.row.catId)">删除</el-button>
        </template>
      </tree-table>
      <!-- 分页 -->
      <el-pagination @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="queryInfo.pageNum"
                     :page-sizes="[5, 10, 20, 50]"
                     :page-size="queryInfo.pageSize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="total"></el-pagination>
    </el-card>

    <!-- 添加分类对话框 -->
    <el-dialog @close="addCateDialogClose"
               title="添加分类"
               :visible.sync="addCateDialogVisible"
               width="40%">
      <el-form :model="addCateForm"
               :rules="addCateFormRules"
               ref="addCateFormRef"
               label-width="100px">
        <el-form-item label="分类名称："
                      prop="catName">
          <el-input v-model="addCateForm.catName"></el-input>
        </el-form-item>
        <el-form-item label="父级分类：">
          <el-cascader v-model="selectedKeys"
                       :options="parentCateList"
                       :props="cascaderProps"
                       @change="parentCateChanged"
                       clearable></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="addCate">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改分类 -->
    <el-dialog title="修改分类"
               :visible.sync="editDialogVisible"
               width="40%"
               @close="editDialogClosed">
      <!-- 内容主体 -->
      <el-form ref="editFormRef"
               :model="editForm"
               :rules="addCateFormRules"
               label-width="70px">
        <el-form-item label="分类名称">
          <el-input v-model="editForm.catName"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="editCate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 商品分类列表
      cateList: [],
      // 查询条件
      queryInfo: {
        catLevel: 3,
        pageNum: 1,
        pageSize: 5
      },
      // 总数据条数
      total: 0,
      // 为Table指定列的定义
      columns: [{
        label: '分类名称',
        prop: 'catName'
      },
      {
        label: '是否有效',
        type: 'template',
        template: 'isok'
      },
      {
        label: '排序',
        type: 'template',
        template: 'order'
      },
      {
        label: '操作',
        type: 'template',
        template: 'opt'
      }],
      // 控制添加分类对话框
      addCateDialogVisible: false,
      // 控制修改分类对话框
      editDialogVisible: false,
      // 添加分类的表单信息
      addCateForm: {
        catName: '',
        catPid: 0,
        catLevel: 0
      },
      // 编辑用户对象
      editForm: {},
      // 添加分类表单验证规则
      addCateFormRules: {
        catName: [{
          required: true, message: '请输入分类名称', trigger: 'blur'
        }]
      },
      // 父级分类列表
      parentCateList: [],
      // 指定级联选择器的配置对象
      cascaderProps: {
        value: 'catId',
        label: 'catName',
        children: 'children',
        expandTrigger: 'hover',
        checkStrictly: true
      },
      // 选中的父级分类id
      selectedKeys: []
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    // 获取商品分类数据
    async getCateList () {
      const { data: res } = await this.$http.post('/api/cate/getByParam?pageNum=' + this.queryInfo.pageNum +
        '&pageSize=' + this.queryInfo.pageSize, { catLevel: this.queryInfo.catLevel })
      if (res.meta.status !== 207) {
        return this.$message.error('获取商品分类失败！')
      } else {
        this.cateList = res.data.list
        this.total = res.data.total
      }
    },
    // 监听 pagesize 改变事件
    handleSizeChange (newSize) {
      this.queryInfo.pageSize = newSize
      this.getCateList()
    },
    // 监听 pagenum 改变事件
    handleCurrentChange (newPage) {
      this.queryInfo.pageNum = newPage
      this.getCateList()
    },
    // 点击打开添加分类对话框
    showAddCateDialog () {
      this.getParentCateList()
      this.addCateDialogVisible = true
    },
    // 获取父级分类数据
    async getParentCateList () {
      const { data: res } = await this.$http.post('/api/cate/getByParam?pageNum=' + this.queryInfo.pageNum +
        '&pageSize=' + this.queryInfo.pageSize, { catLevel: 2 })
      if (res.meta.status !== 207) {
        return this.$message.error('获取父级分类信息失败！')
      } else {
        this.parentCateList = res.data.list
      }
    },
    // 选择器发生变化时触发
    parentCateChanged () {
      if (this.selectedKeys.length > 0) {
        this.addCateForm.catPid = this.selectedKeys[this.selectedKeys.length - 1]
        this.addCateForm.catLevel = this.selectedKeys.length
      } else {
        this.addCateForm.catPid = 0
        this.addCateForm.catLevel = 0
      }
    },
    // 点击按钮添加新的分类
    addCate () {
      this.$refs.addCateFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('请输入分类名称！')
        } else {
          const { data: res } = await this.$http.post('/api/cate/addCate', this.addCateForm)
          if (res.meta.status !== 201) {
            return this.$message.error('添加分类失败！')
          } else {
            this.getCateList()
            this.addCateDialogVisible = false
            return this.$message.success('添加分类成功！')
          }
        }
      })
    },
    // 监听对话框关闭事件
    addCateDialogClose () {
      this.$refs.addCateFormRef.resetFields()
      this.selectedKeys = []
      this.addCateForm.catPid = 0
      this.addCateForm.catLevel = 0
    },
    editDialogClosed () {

    },
    // 展示修改用户对话框
    async showEditDialog (catId) {
      this.editDialogVisible = true
      const { data: res } = await this.$http.get('/api/cate/getById?catId=' + catId)
      if (res.meta.status !== 207) {
        return this.$message.error('查询分类信息失败！')
      } else {
        this.editForm = res.data
      }
    },
    // 修改分类
    editCate () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('/api/cate/updCate', { catId: this.editForm.catId, catName: this.editForm.catName })
        if (res.meta.status !== 203) {
          return this.$message.error('更新分类信息失败！')
        } else {
          this.editDialogVisible = false
          this.getCateList()
          return this.$message.success('更新分类信息成功！')
        }
      })
    },
    // 根据id删除用户信息
    async removeUserById (catId) {
      // 弹框确认
      const confirmResult = await this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除操作！')
      } else {
        const { data: res } = await this.$http.get('/api/cate/delCate?catId=' + catId)
        if (res.meta.status !== 205) {
          return this.$message.error('删除分类失败！')
        } else {
          this.getCateList()
          return this.$message.success('删除分类成功！')
        }
      }
    }
  }
}
</script>

<style lang="less" scoped>
.treeTable {
  margin-top: 15px;
}
.el-cascader {
  width: 100%;
}
</style>
